//: src/com/silvtar/io/SSFile.java
/* 
 * Created by 朴晟宁 <piaosn@gmail.com> on 4/21/2013. 
 * Copyright (c) 2013 朴晟宁. All rights reserved.
 * 
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program;
 * 
 * Modify History:
 * Date        Version    Description
 * 5/20/2013   0.1        Create The Class
 */
package com.silvtar.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;

import com.silvtar.sync.controller.SilverySyncInit;
import com.silvtar.util.Android;
import com.silvtar.util.SSPlatform;

/**
 * 文件类，本类提供了文件的随机字符读写功能
 * 
 * @author 朴晟宁/Silvtar
 * @author piaosn@gmail.com
 * @version 0.1
 */
public class SSFile {

    InputStream inputStream;
    InputStreamReader reader;
    BufferedReader bufferedReader;
    RandomAccessFile randomAccessFile;
    String           filePath;

    // --------------------------------------------------------------
    /**
     * 以文件名构造对象,支持安卓。
     * @param filePath 文件路径
     * @param mode 打开文件的方式，有rw与r可选
     */
    public SSFile(String filePath, String mode) {
        this.filePath = filePath;
        
        if (SSPlatform.platform == SSPlatform.ANDROID) {
            inputStream = Android.openAsset(filePath);
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
        } else {
            try {
                randomAccessFile = new RandomAccessFile(filePath, mode);
            } catch (FileNotFoundException e) {
                StdOut.printErr("文件：" + filePath + " 不存在");
                e.printStackTrace();
            }
        }
        
    }

    /**
     * 以文件构造对象
     * @param filePath 要打开的文件
     * @param mode 打开文件的方式，有rw与r可选
     */
    public SSFile(File file, String mode) {
        this.filePath = file.getName();
        try {

            randomAccessFile = new RandomAccessFile(file, mode);
        } catch (FileNotFoundException e) {
            StdOut.printErr("文件：" + file.getName() + " 不存在");
            e.printStackTrace();
        }
    }

    // --------------------------------------------------------------
    /**
     * 获得文件指针位置
     * @return 文件指针位置
     */
    public long getFilePointer() {
        long position = 0;
        try {
            position = randomAccessFile.getFilePointer();
        } catch (IOException e) {
            StdOut.printErr("从文件：" + filePath + " 获取文件指针失败");
            e.printStackTrace();
        }
        return position;
    }

    /**
     * 将文件指针跳转到指定位置
     * @param position 要跳转到的位置
     */
    public void seek(long position) {
        try {
            randomAccessFile.seek(position);
        } catch (IOException e) {
            StdOut.printErr("在文件：" + filePath + " 中，跳转位置时失败");
            e.printStackTrace();
        }
    }

    /**
     * 将文件指针跳转到文件末尾
     */
    public void seekLast() {
        try {
            seek(randomAccessFile.length());
        } catch (IOException e) {
            StdOut.printErr("从文件：" + filePath + " 中，跳转到最后时失败");
            e.printStackTrace();
        }
    }

    /**
     * 关闭文件
     */
    public void close() {
        try {
            randomAccessFile.close();
        } catch (IOException e) {
            StdOut.printErr("关闭文件：" + filePath + " 失败");
            e.printStackTrace();
        }
    }

    // --------------------------------------------------------------
    /**
     * 读取一行数据（EUS编码）
     * @return 读取到的字符串
     */
    public String readLine() {
        String line = null;
        if (SSPlatform.platform == SSPlatform.ANDROID) {
            try {
                line = bufferedReader.readLine();
            } catch (IOException e) {
                StdOut.printErr("从文件：" + filePath + " 中读取整行失败");
                e.printStackTrace();
            }
        } else {
            try {
                line = randomAccessFile.readLine();
            } catch (IOException e) {
                StdOut.printErr("从文件：" + filePath + " 中读取整行失败");
                e.printStackTrace();
            }
        }
        
        return line;
    }

    /**
     * 写入字符串（EUS编码）
     * @param string 要写入的字符串
     */
    public void writeBytes(String string) {
        try {
            randomAccessFile.writeBytes(string);
        } catch (IOException e) {
            StdOut.printErr("向文件：" + filePath + " 中读取写入字符串失败");
            e.printStackTrace();
        }
    }

    /**
     * 写入字符串（UTF-8）
     * @param string 要写入的字符串
     */
    public void writeUTF(String string) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(
                    new FileOutputStream(filePath, true), "utf-8");
            writer.write(string);
        } catch (UnsupportedEncodingException e1) {
            StdOut.printErr("不支持的编码类型");
            e1.printStackTrace();
        } catch (FileNotFoundException e1) {
            StdOut.printErr("文件：" + filePath + " 不存在");
            e1.printStackTrace();
        } catch (IOException e) {
            StdOut.printErr("向文件：" + filePath + " 中读取写入字符串失败");
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
